<template>
  <div class="ChargebeePrice">
    <paywall-header path="ChargebeePrice"></paywall-header>
    <el-card class="box-card" v-loading="loading">
      <el-alert
          title="Note: This page will modify the price of bundles and add-on in chargebee, if vou save it, the MSPbots will sell it according to the new price"
          type="info"
          :closable="false">
      </el-alert>
      <el-row style="margin-top: 20px">
        <el-col :span="6">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="Discount">
              <el-input v-model="discount" placeholder=""></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6" :offset="12">
          <el-input
              v-model="search"
              prefix-icon="el-icon-search"
              size="mini"
              placeholder="Search"/>
        </el-col>
      </el-row>
      <el-table
          :default-sort = "{prop: 'name', order: 'ascending'}"
          :data="bundles.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
          @cell-click="edit"
          style="width: 100%">
        <el-table-column
            prop="name"
            sortable
            label="Bundles">
        </el-table-column>
        <el-table-column
            label="Monthly Price">
          <template slot-scope="scope">
            <div v-show="scope.row.isEdit">
              <el-input style="width: 50%; margin-right: 20px" size="mini" v-model="scope.row.editPrice"></el-input>
              <el-button type="info" icon="el-icon-close" size="mini" @click.stop="cancel(scope.row)"></el-button>
              <el-button type="primary" icon="el-icon-check" size="mini" @click.stop="changePrice(scope.row)"></el-button>
            </div>
            <span v-show="!scope.row.isEdit">{{(scope.row.monthPrice.price / 100).toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column
            label="Yearly Price">
          <template slot-scope="scope">
            <span style="display: inline-block; width: 80px">{{(scope.row.monthPrice.price * discount * 12 / 100).toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column
            label="Action">
          <template slot-scope="scope">
            <el-button type="primary" v-loading="scope.row.loading" icon="el-icon-upload2" size="mini" @click.stop="savePrice(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-table
          :default-sort = "{prop: 'name', order: 'ascending'}"
          :data="addOn.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
          @cell-click="edit"
          style="width: 100%">
        <el-table-column
            prop="name"
            sortable
            label="Add-on">
        </el-table-column>
        <el-table-column
            label="Monthly Price">
          <template slot-scope="scope">
            <div v-show="scope.row.isEdit">
              <el-input style="width: 50%; margin-right: 20px" size="mini" v-model="scope.row.editPrice"></el-input>
              <el-button type="info" icon="el-icon-close" size="mini" @click.stop="cancel(scope.row)"></el-button>
              <el-button type="primary" icon="el-icon-check" size="mini" @click.stop="changePrice(scope.row)"></el-button>
            </div>
            <span v-show="!scope.row.isEdit">{{scope.row.monthPrice &&( scope.row.monthPrice.price / 100).toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column
            label="Yearly Price">
          <template slot-scope="scope">
            <span v-if="scope.row.monthPrice" style="display: inline-block; width: 80px">{{(scope.row.monthPrice.price * discount * 12 / 100).toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column
            label="Action">
          <template slot-scope="scope">
            <el-button v-if="scope.row.monthPrice" type="primary" icon="el-icon-upload2" size="mini" @click.stop="savePrice(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-table
          :default-sort = "{prop: 'name', order: 'ascending'}"
          :data="charge.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
          @cell-click="edit"
          style="width: 100%">
        <el-table-column
            prop="name"
            sortable
            label="Charges">
        </el-table-column>
        <el-table-column
            label="Price">
          <template slot-scope="scope">
            <div v-show="scope.row.isEdit">
              <el-input style="width: 50%; margin-right: 20px" size="mini" v-model="scope.row.editPrice"></el-input>
              <el-button type="info" icon="el-icon-close" size="mini" @click.stop="cancel(scope.row)"></el-button>
              <el-button type="primary" icon="el-icon-check" size="mini" @click.stop="changePrice(scope.row)"></el-button>
            </div>
            <span v-show="!scope.row.isEdit">{{(scope.row.monthPrice.price / 100).toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop=""
            label="">
        </el-table-column>
        <el-table-column
            label="Action">
          <template slot-scope="scope">
            <el-button v-if="scope.row.monthPrice" type="primary" icon="el-icon-upload2" size="mini" @click.stop="savePrice(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import paywallHeader from "@/views/modules/mspbots/payWallManage/paywallHeader.vue";

export default {
  name: "chargebeePrice",
  components: {
    paywallHeader,
  },
  data () {
    return {
      loading: false,
      discount: '',
      bundles: [],
      addOn: [],
      charge: [],
      search: ''
    }
  },
  computed: {
    discounts () {
      return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'pay_wall_discount').dataList[0].dictValue
    },
  },
  watch: {
    discounts: {
      handler: function (val) {
        this.discount = (100 - Number(val)) / 100
      },
      immediate: true
    }
  },
  methods: {
    edit (row, column) {
      if (row.isEdit) {
        return false
      }
      if (column.label === 'Monthly Price') {
        this.$set(row, 'editPrice', row.monthPrice.price / 100)
        this.$set(row, 'isEdit', true)
      }
      if (column.label === 'Price') {
        this.$set(row, 'editPrice', row.monthPrice.price / 100)
        this.$set(row, 'isEdit', true)
      }
    },
    cancel (row) {
      row.editPrice = row.monthPrice.price
      this.$set(row, 'isEdit', false)
    },
    changePrice (row) {
      row.monthPrice.price = row.editPrice * 100
      this.$set(row, 'isEdit', false)
    },
    savePrice (row) {
      this.$confirm('Please confirm if you save the new price?', 'Alert', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(async () => {
        if (row.yearPrice) {
          row.yearPrice.price = row.monthPrice.price * this.discount * 12
        }
        this.$set(row, 'loading', true)
        await this.updatePrice(row, 'month')
        if (row.type !== "charge") {
          setTimeout(async () => {
             await this.updatePrice(row, 'year')
            this.$set(row, 'loading', false)
          }, 2000)
        } else {
          this.$set(row, 'loading', false)
        }
        this.$set(row, 'isEdit', false)
      }).catch(() => {
        // this.cancel(row)
      });
    },
    getData () {
      this.loading= true
      const { chargebeePrice } = this.$interface.pay
      chargebeePrice().then(res => {
        const list = res.data.data.chargebeeItemsList.filter(item => {
          return item.chargebeeItemPricesList
        })
        const data = list.map(item => {
          item.chargebeeItemPricesList && item.chargebeeItemPricesList.map(items => {
            if (items.tiers) {
              items.price = items.tiers[1].price
            }
          })
          if (item.type === 'charge') {
            item.monthPrice = item.chargebeeItemPricesList[0]
          } else {
            item.yearPrice = this._.find(item.chargebeeItemPricesList, {periodUnit: 'year'})
            item.monthPrice = this._.find(item.chargebeeItemPricesList, {periodUnit: 'month'})
          }
          return item
        })
        this.bundles = this.filterTypeData('plan', data)
        this.addOn = this.filterTypeData('addon', data)
        this.charge = this.filterTypeData('charge', data)
        this.loading = false
      })
    },
    filterTypeData (type, data) {
      return this._.filter(data, item => {
        return item.type === type && item.chargebeeItemPricesList
      })
    },
    async updatePrice (item, type) {
      const key = type === 'month' ? 'monthPrice' : 'yearPrice'
      if(item.metadata && item.metadata[type]) {
        item.metadata[type].price = Number(item[key].price) / 100
      }
      if (item[key].tiers) {
        item[key].tiers[1].price = Number(item[key].price)
        item[key].tiers = item[key].tiers.map(item => {
          let obj = {}
          Object.keys(item).map(items => {
            obj[this._.camelCase(items)] = item[items]
          })
          return obj
        })
      }
      const params = {
        otherId: item.otherId,
        otherPricesId: item[key].otherId,
        metadata: item.metadata,
        price: Number(item[key].price),
        addonTiersDTOList: item[key].tiers ? item[key].tiers : []
      }
      const { chargebeePriceUpdate } = this.$interface.pay
      const { data } = await chargebeePriceUpdate(params)
      if (data.code === 0) {
        this.$message.success(data.msg)
      } else {
        this.$message.error(data.msg)
      }
    }
  },
  created () {
    this.getData()
  }
}
</script>

<style scoped>

</style>
